const fs = require("fs");
var shell = require("shelljs");
var { themeList, getShell, cuurentResolve } = require("./tool");
const { resolve } = require("path");
const gitplace = require("./gitplace");

let errThemeNames = [];
function pullMaster(file) {
    console.log("----------------执行" + file + " master拉取");
    shell.cd(cuurentResolve(`/src/theme/${file}`));
    shell.exec(`git checkout master`);
    const result = getShell("git pull origin master", `----------------${file}拉取master失败`);
    if (!result) {
        errThemeNames.push(file);
    }
    shell.cd(cuurentResolve());
    return true;
}

function cloneMaster(url) {
    const name = url.split("/").pop().split(".")[0];
    console.log("----------------执行" + name + "master克隆");
    shell.cd(cuurentResolve(`/src/theme`));
    let data = shell.exec(`git clone ${url}`);
    if(data.code != 0){
        console.log(data.stdout)
        errThemeNames.push(name);
        return true
    }
    console.log(`${name}模板克隆成功`)
    
    return true;
}

function pushMaster(file) {
    console.log("----------------执行" + file + " master推送");
    shell.cd(cuurentResolve(`/src/theme/${file}`));
    if(getShell("git pull origin master", `----------------${file}拉取master失败`)){
        shell.exec(`git checkout master`);
        shell.exec(`git add .`);
        shell.exec(`git commit -m'fix'`);
        if (!getShell("git push origin master", `----------------${file}推送master失败`)) {
            errThemeNames.push(file);
        }
    }else{
        errThemeNames.push(file);
    }
 
    shell.cd(cuurentResolve());
    return true;
}

function pushAll() {
    // 拉去所有模版
    const list = themeList();
    list.forEach((item) => {
        if (!["customtemp29831", "customtemp39391"].includes(item)) {
            pushMaster(item);
        }
    });
    console.log("push失败模版：", errThemeNames);
}

function cloneAll() {
    // 克隆所有模板
    const targetDir = resolve(__dirname, '../../src/theme');
    if (!fs.existsSync(targetDir)) {
        console.log(`创建目标文件夹: ${targetDir}`);
        fs.mkdirSync(targetDir, { recursive: true });
    }
    gitplace.forEach((item) => {
        cloneMaster(item);
    });
    console.log("clone失败模版:", errThemeNames);
}

function pullAll() {
    // 拉去所有模版
    const list = themeList();
    list.forEach((item) => {
        if (!["customtemp29831", "customtemp39391"].includes(item)) {
            pullMaster(item);
        }
    });
    console.log("pull失败模版：", errThemeNames);
}
module.exports = { pushAll, pullAll,cloneAll };
